package uhasselt.ontologyplugin;

import net.sf.saxon.s9api.XdmNode;
import net.sf.saxon.s9api.Processor;
import net.sf.saxon.s9api.DocumentBuilder;
import net.sf.saxon.s9api.XsltCompiler;
import net.sf.saxon.s9api.XsltTransformer;
import net.sf.saxon.s9api.XsltExecutable;
import net.sf.saxon.s9api.XdmDestination;
import net.sf.saxon.s9api.SaxonApiException;
import java.io.StringReader;
import java.io.File;
import javax.xml.transform.stream.StreamSource;

public class RemoveNameSpaces {
	
	
	private XsltExecutable _removeNameSpaces = null;
	static private RemoveNameSpaces _instance = null;
	
	static public RemoveNameSpaces getInstance(){
		if(_instance == null)
			_instance = new RemoveNameSpaces();
		return _instance;
	}
	
	/**
	 * Removes all the namespace declarations from subtags and moves them up into the root
	 * @param n Xml document
	 */ 
	public XdmNode transform(XdmNode n){
		try {
			XsltTransformer xsltTransformer = _removeNameSpaces.load();
			XdmDestination result = new XdmDestination();
			xsltTransformer.setDestination(result);
			xsltTransformer.setSource(n.asSource());
			xsltTransformer.transform();
			return result.getXdmNode();
		} catch (SaxonApiException e){
			e.printStackTrace();
		}
		return null;
	}
	/**
	 * Constructor
	 */
	public RemoveNameSpaces(){
		try {
			Processor processor = ToSkosTransformer.getProcessorInstance();
			DocumentBuilder documentBuilder = processor.newDocumentBuilder();
			XsltCompiler xsltCompiler = processor.newXsltCompiler();
			String query = "<xsl:stylesheet "
						   		+"xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" "
			  					+"version=\"2.0\" "
			  				    +"xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" "
			  					+"exclude-result-prefixes=\"xs\">"

			  					+"<xsl:template match=\"@* | node()\">"
			    					+"<xsl:copy copy-namespaces=\"no\">"
			      						+"<xsl:apply-templates select=\"@* , node()\"/>"
			    					+"</xsl:copy>"
			  					+"</xsl:template>"
								+"<xsl:template match=\"/*\">"
			    					+"<xsl:copy>"
			      						+"<xsl:copy-of select=\"descendant::*/namespace::*\"/>"
			      						+"<xsl:apply-templates select=\"@* , node()\"/>"
			    					+"</xsl:copy>"
			  					+"</xsl:template>"
							+"</xsl:stylesheet>";
			_removeNameSpaces = xsltCompiler.compile(new StreamSource(new StringReader(query)));
		} catch (SaxonApiException e){
			e.printStackTrace();
		}
	}
}